package com.jinx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.jinx.listener.ExcelListener;
import com.jinx.model.template.CourseExportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jixia
 * @date 2021/10/21 14:48
 * @description
 */
@Slf4j
public class ExcelController {

    public boolean downLoadTemplate(HttpServletResponse response) {
        CourseExportTemplate courseExportTemplate = new CourseExportTemplate();
        courseExportTemplate.setAcademyName("计算机学院");
        courseExportTemplate.setClassHour("6");
        courseExportTemplate.setClassPoint("30");
        courseExportTemplate.setCode("A2001");
        courseExportTemplate.setCourseCategory("理工类");
        courseExportTemplate.setCourseNature("必修");
        courseExportTemplate.setCourseType("理工");
        courseExportTemplate.setName("LINUX");
        courseExportTemplate.setScore("100");
        List<CourseExportTemplate> list = new ArrayList<>();
        list.add(courseExportTemplate);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // URLEncoder.encode可以防止中文乱码
            String cFileName = URLEncoder.encode("课程代码", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + cFileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), CourseExportTemplate.class).sheet().doWrite(list);
        } catch (IOException e) {
            log.error("excel下载失败:错误信息：{}", e.toString());
            return false;
        }
        return true;
    }

    public String importCourse(MultipartFile file) {
        //获取导入Excel文件名
        String fileName = file.getOriginalFilename();
        if (ObjectUtils.isEmpty(fileName)) {
            log.error("导入失败，文件名为空");
        }
        ExcelListener listener = new ExcelListener();
        try {
            EasyExcel.read(file.getInputStream(), CourseExportTemplate.class, listener).sheet().doRead();
        } catch (IOException e) {
            log.error("Excel写入失败");
            e.printStackTrace();
        }
        //获取解析后的课程数据
        List<CourseExportTemplate> courseList = JSON.parseArray(JSON.toJSONString(listener.getDatas()), CourseExportTemplate.class);
        //这里调用了通用Mapper方法存入数据库
        courseList.forEach(k -> System.out.println());
        return "导入成功";
    }


}

